<template>
  <el-upload
    class="upload-avatar"
    action="fakeupload"
    accept="image/jpeg,image/gif,image/png"
    multiple
    :show-file-list="false"
    :http-request="uploadSectionFile"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">
      只能上传jpg/png文件，且不超过500kb
    </div>
  </el-upload>
</template>

<script>
  import uploadFile from '@/utils/ajax'
  import { getUploadUrl } from '@/api/fileApi'

  export default {
    name: 'UploadAvatar',
    props: {
      url: {
        type: String,
        default: function () {
          return ''
        },
      },
    },
    data() {
      return {}
    },
    created() {},
    methods: {
      handleAvatarSuccess(res, file) {
        const iurl = file.raw.downloadURL
        if (iurl === undefined) {
          Message({
            message: '上传失败' + res.message,
            type: 'fail',
            duration: 1 * 1000,
          })
          return
        }
        this.$emit('update:url', iurl)
      },
      beforeAvatarUpload(file) {
        let isImg = file.type === 'image/jpeg'
        isImg = isImg || file.type === 'image/png'
        const isLt2M = file.size / 1024 / 1024 < 10

        if (!isImg) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!')
        }
        return isImg && isLt2M
      },
      uploadSectionFile(param) {
        getUploadUrl(param.file.name).then((resp) => {
          param.action = resp.data['putURL']
          param.file.downloadURL = resp.data['getURL']
          uploadFile(param)
        })
      },
    },
  }
</script>
